package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: tensquare_parent
 * @BelongsPackage: com.tensquare.spit.service
 * @Author: yang
 * @CreateTime: 2019-03-06 10:57
 * @Description: ${Description}
 */
@Service
@Transactional
public class SpitService  {
     @Autowired
     private SpitDao spitDao;
     @Autowired
     private IdWorker idWorker;

     @Autowired
     private MongoTemplate mongoTemplate;

    /**
     * 发布吐槽 要将用户不填写的地方设置初始值
     */
    public void save(Spit spit){
        spit.set_id(idWorker.nextId()+"");
        spit.setPublishtime(new Date()); //发布日期
        spit.setVisits(0); //浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态

        //如果当前添加的吐槽 有父节点 那么父节点的吐槽回复数要加1
        if(spit.getParentid()!=null&&!"".equals(spit.getParentid())){
            Query query=new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));//更新父节点的吐槽数
            Update update=new Update();
            update.inc("comment",1);//父节点回复数加1
            mongoTemplate.updateFirst(query,update,"spit");
        }

        spitDao.save(spit);
    }


    //点赞
    public void thumbup(String spitId) {
        //方式一 ：每次都要从数据库查 效率很低
//        Spit spit = spitDao.findById(spitId).get();
//        spit.setThumbup((spit.getThumbup()==null?0:spit.getThumbup())+1);
//        spitDao.save(spit);

        //方式二：使用原生mongo命令自增  db.spit.update("_id":"1",{$inc:{thumhup:NumberInt(1)}})
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is("1"));
        Update update=new Update();
        update.inc("thumpbup",1);
        mongoTemplate.updateFirst(query,update,"spit");

    }

     public List<Spit> findAll(){
         return  spitDao.findAll();
     }

     public Spit findById(String id){
         return  spitDao.findById(id).get(); //新版本findById  老版本 findOne
     }




     public void update(Spit spit){
         spitDao.save(spit);
     }

     public void deleteById(String id){
         spitDao.deleteById(id);
     }


     public Page<Spit> findByParentId(String parentid,int page,int size){
         Pageable pageable= PageRequest.of(page-1,size);
         return spitDao.findByParentid(parentid,pageable);

     }




}
